<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

interface InState {
    /** 数据状态 */
    loading: boolean;
    /** 附件地址 */
    fileUrl: string;
}
/** 数据 */
let state = ref<InState>({
    loading: false,
    fileUrl: ""
})
const tableDialogVisible = ref(false)

const headerCellStyle = {
    padding:'10px 0',
    background: '#CCDDF9',
    color: '#3D4755'
}

// 自定义合计行
const getSummaries = (param: { columns: any[], data: any[] }) => {
  const { columns, data } = param;
  const sums: string[] = [];
  
  // 遍历每一列
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';  // 第一列显示 "Total"
      return;
    }

    // 只对 price 和 quantity 列进行合计
    if (['weight', 'bulk'].includes(column.property)) {
      const values = data.map(item => Number(item[column.property]));
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => prev + curr, 0).toFixed(2); // 保留两位小数
      } else {
        sums[index] = 'N/A';
      }
    } else {
      sums[index] = ''; // 其他列不显示合计
    }
  });

  return sums;
};

interface SpanMethodProps {
  row: any
  column: any
  rowIndex: number
  columnIndex: number
}

const mergeCells = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
    if (column.property === 'areaName') {
    // 合并相同的 "name" 列
    let previousRow = layersData.value[rowIndex - 1];
    if (previousRow && previousRow.areaName === row.areaName) {
      return [0, 0]; // 如果和上一行的 "name" 相同，则合并
    }

    let rowspan = 1;
    for (let i = rowIndex + 1; i < layersData.value.length; i++) {
      if (layersData.value[i].areaName === row.areaName) {
        rowspan++;
      } else {
        break;
      }
    }
    return [rowspan, 1];
  }
}

import { FuelWorkTInventoryInfo, bunkerFileUrl } from "@/api";

const detailData = ref<any>({})
const layersData = ref<any>([])
const operationLogs = ref<any>([])
const getFuelWorkTInventoryInfo = () => {
  state.value.loading = true;
    FuelWorkTInventoryInfo(eId.value).then((res: any) => {
        if (res.code === 1) {
            ElMessageBox.alert(
                res.msg,
                '错误',
                {
                    type: 'error',
                    showClose: false,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '确定',
                    callback: (action: any) => {
                        router.push(`/stock/record`);
                    }
                }
            );

            return;
        }

        // console.log('详情----',res.data)
        detailData.value = res.data.detail;
        layersData.value = res.data.layers;
        operationLogs.value = res.data.operationLogs;

        if (detailData.value.imageNotAvailable) {
            detailData.value.imgUrl = "../assets/img/ph_3d.jpg";
        }
        else {
            var fileName =
                state.value.fileUrl +
                detailData.value.parentBunkerId +
                "Stockyard" +
                "/" +
                detailData.value.fileName +
                "/" +
                detailData.value.fileName +
                (detailData.value.useNewImage ? ".txt.jpg" : ".txt.bmp");

            detailData.value.imgUrl = fileName;
        }
    }).finally(() => {
      state.value.loading = false;
    })
}

const eId = ref<any>('')
onMounted(() => {
    console.log(route.query.eId);
    eId.value = route.query.eId
    bunkerFileUrl().then(res => {
        state.value.fileUrl = res.data;
    })
    getFuelWorkTInventoryInfo();
});

function view3D(id: number, executeId?: number) {
    if (!executeId) {
        router.push(`/stock/yard?bunkerId=${id}`);
    }
    else {
        router.push(`/stock/yard?bunkerId=${id}&executeId=${executeId}`);
    }
}

</script>
<template>
    <div class="record_info" v-loading="state.loading">
        <div class="table_info">
            <table>
                <colgroup>
                    <col width="20%">
                    <col width="20%">
                    <col width="20%">
                    <col width="20%">
                    <col width="20%">
                </colgroup>
                <tr>
                    <th>煤场名称</th>
                    <td>{{ detailData.bunkerName }}</td>
                    <td></td>
                    <th>登记人</th>
                    <td>{{ detailData.userName }}</td>
                </tr>
                <tr>
                    <th>盘煤时间</th>
                    <td>{{ detailData.executeTime }}</td>
                    <td></td>
                    <th>密度</th>
                    <td>{{ detailData.density }}</td>
                </tr>
                <tr>
                    <th>盘煤重量</th>
                    <td>{{ detailData.coalWeight }}吨</td>
                    <td></td>
                    <th>盘煤体积</th>
                    <td>{{ detailData.coalBulk }}</td>
                </tr>
                <tr>
                    <th>与上次盘煤重量差</th>
                    <td>
                        <p v-if="detailData.differenceOfCoalWeight>0" class="red">{{ detailData.differenceOfCoalWeight }}吨</p>
                        <p v-if="detailData.differenceOfCoalWeight<0" class="green">{{ detailData.differenceOfCoalWeight }}吨</p>
                        <p v-if="detailData.differenceOfCoalWeight==0" >{{ detailData.differenceOfCoalWeight }}吨</p>
                    </td>
                    <td></td>
                    <th>与前一次盘煤体积差</th>
                    <td>
                        <p v-if="detailData.differenceOfCoalBulk==0" >{{ detailData.differenceOfCoalBulk }}</p>
                        <p v-if="detailData.differenceOfCoalBulk>0" class="red">{{ detailData.differenceOfCoalBulk }}</p>
                        <p v-if="detailData.differenceOfCoalBulk<0" class="green">{{ detailData.differenceOfCoalBulk }}</p>
                    </td>
                </tr>
                <tr>
                    <th>存煤报表</th>
                    <td>
                      <a :href="`${state.fileUrl}${detailData.parentBunkerId}Stockyard/${detailData.fileName}/${detailData.fileName}.xlsx`" target="_blank" download>
                        {{ detailData.fileName }}
                      </a>  
                        <!-- <a href="#" class="table_link">{{ detailData.fileName }}</a> -->
                        <!-- <a href="#" style="margin-left: 20px;font-weight: bold;color: #2565C8;">下载</a> -->
                    </td>
                    <td></td>
                    <th>存煤图片</th>
                    <td>
                        <el-image :src="detailData.imgUrl" fit="contain" @click="view3D(detailData.parentBunkerId, detailData.executeId)"></el-image>
                    </td>
                </tr>
            </table>
            <h3>存煤明细</h3>
        </div>

        <el-table
            :data="layersData"
            style="width: 100%;"
            border
            show-summary
            :summary-method="getSummaries"
            :span-method="mergeCells"
            :highlight-current-row="false"
            :header-cell-style="headerCellStyle"
            >
            <el-table-column prop="areaName" label="分区名称"  />
            <el-table-column prop="firstCode" label="一次编码" />
            <el-table-column prop="bunkerTypeName" label="所属煤种" />
            <el-table-column prop="weight" label="堆体重量" />
            <el-table-column prop="bulk" label="堆体体积" />
        </el-table>
        <div class="table_info">
            <h3>备注</h3>
            <div class="beiz" v-if="!operationLogs.length">
                {{ detailData.remark||'无' }}
            </div>
            <div class="beiz" v-else>
                <div v-for="logs in operationLogs" :key="logs.item1">
                  <span>{{ logs.item1 }}：</span>
                  <span>{{ logs.item2 }}</span>
                </div>
            </div>
        </div>

        <div class="record_info_btn">
            <el-button color="#2565C8">导出</el-button>
            <!-- <el-button color="#2565C8" @click="tableDialogVisible = true">修改</el-button> -->
            <el-button color="#2565C8" @click="router.go(-1)">关闭</el-button>
        </div>
    </div>

    <!-- 弹出框 -->
    <el-dialog v-model="tableDialogVisible" width="400" :align-center="true" center>
        <div class="table_dialog">
            <img src="../../assets/img/ico_6.png" alt="">
            <strong>警告</strong>
            <span>
                盘煤体积与各明细体积之和不一致！
            </span>
        </div>
    </el-dialog>

</template>
<style scoped lang="scss">
.el-table{
    --el-table-row-hover-bg-color:#fff
}
</style>
<style>

</style>